<style lang="scss">

</style>
<template>
  <div v-if="!item.meta.hidden">
    <!-- 没有子路由 -->
    <template v-if="hasOneShowingChild(item.children,item)">
      <el-menu-item :index="resolvePath(onlyOneChild.path)">
        <i :class="onlyOneChild.meta.iconCls" />
        <span slot="title">{{ onlyOneChild.meta.name }}0</span>
      </el-menu-item>
    </template>
    <!-- 有子路由 -->
    <el-submenu v-else :index="resolvePath(item.path)">
      <template slot="title">
        <i :class="item.meta.iconCls" />
        <span>{{ item.meta.name }}1 </span>
      </template>
      <el-menu-item v-for="child in item.children" :key="child.path" :index="resolvePath(child.path)">
        <i :class="child.meta.iconCls" />
        <span slot="title">{{ child.meta.name }}2 </span>
      </el-menu-item>
      <!-- <sidebar-item
        v-for="(child,index) in item.children"
        :key="index"
        :item="child"
        :base-path="resolvePath(child.path)"
      /> -->
    </el-submenu>
  </div>
</template>

<script>
import path from 'path'
export default {
  name: 'SidebarItem',
  props: {
    item: {
      type: Object,
      required: true
    },
    basePath: {
      type: String,
      default: ''
    },
    activeMenu: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      onlyOneChild: null
    }
  },
  created() {},
  methods: {
    hasOneShowingChild(children = [], parent) {
      const showingChildren = children.filter(item => {
        if (item.hidden) {
          return false
        } else {
          // Temp set(will be used if only has one showing child)
          this.onlyOneChild = item
          return true
        }
      })
      // When there is only one child router, the child router is displayed by default
      if (showingChildren.length === 1) {
        return true
      }
      // Show parent if there are no child router to display
      if (showingChildren.length === 0) {
        this.onlyOneChild = {
          ...parent,
          path: '',
          noShowingChildren: true
        }
        return true
      }
      return false
    },
    resolvePath(routePath) {
      return path.resolve(this.basePath, routePath)
    }
  }
}
</script>

